﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XWord.Fundamental.Domain;
using XWord.WPF.ApplicationFramework;
using Caliburn.Core.Metadata;
using XWord.Fundamental.Domain.Services;
using System.ComponentModel;

namespace XWord.GUI.Presenters.Interface
{
    public interface IWordBehavior
    {
        bool Add(string name);

        void Remove(string name);

        void RaiseWordEventHandler(Word word, WordAction action);

        bool RaiseWordSearchEventHandler(string word);

        event WordEventHandler WordEventHandler;

        event WordCancelEventHandler WordSearchEventHandler;

        //event WordEventHandler WordChangedEventHandler;
    }

    public enum WordAction
    {
        Add,
        Remove,
        SelectedItemChanged
    }

    public class WordEventArgs : EventArgs
    {
        public WordAction Action { get; set; }

        public Word Word { get; set; }

        
    }

    public class WordCancelEventArgs : CancelEventArgs
    {
        public string Word { get; set; }
    }

    public delegate void WordCancelEventHandler(object sender, WordCancelEventArgs args);

    public delegate void WordEventHandler(object sender,WordEventArgs args);

    [Singleton(typeof(IWordBehavior))]
    public class WordBehavior : IWordBehavior
    {
        public bool Add(string name)
        {
            RemotingServiceFactory.GetWordService().WordAction(name, 0);
            return true;
        }

        public void Remove(string name)
        {
            RemotingServiceFactory.GetWordService().WordAction(name, 1);
        }

        public void RaiseWordEventHandler(Word word, WordAction action)
        {
            var args = new WordEventArgs() { Word = word, Action = action };
            switch (action)
            {
                case WordAction.Add:
                    Add(word.Name);
                    break;
                case WordAction.Remove:
                    Remove(word.Name);
                    break;
                default:
                    break;
            }
            if (WordEventHandler != null)
            {
                WordEventHandler(this, args);
            }
        }

        public bool RaiseWordSearchEventHandler(string word)
        {
            var args = new WordCancelEventArgs() { Word = word };
            if (WordSearchEventHandler != null)
            {
                this.WordSearchEventHandler(this, args);
            }
            return args.Cancel;
        }

        public event WordEventHandler WordEventHandler;


        public event WordCancelEventHandler WordSearchEventHandler;
    }

}
